package com.sky.service.impl;

import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description:
 * @author: ManolinCoder
 * @time: 2024/5/26
 */
@Service
public class DishServiceImpl implements DishService {


    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;



    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     */
  @Transactional //涉及到多个数据表的操作，因此这个地方要保证数据的一致性。同时需要开启注解方式的事务控制（在我们启动类上已经开启了注解方式的事务控制）
    public void savewithFlavor(DishDTO dishDTO) {

      Dish dish = new Dish();

      BeanUtils.copyProperties(dishDTO,dish); //要对应

      //向菜品表插入一条数据
      dishMapper.insert(dish);

      //获取insert语句生成的主键值
      Long dishId = dish.getId();

      List<DishFlavor> flavors = dishDTO.getFlavors();
      if (flavors != null && flavors.size() >0) {
          flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));

          //向口味表插入n条数据
          dishFlavorMapper.insertBatch(flavors);
      }


  }
}
